package com.android.wellcherish.workclock.view;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.wellcherish.workclock.R;
import com.android.wellcherish.workclock.bean.data.GroupRecord;
import com.android.wellcherish.workclock.bean.data.IBaseBean;
import com.android.wellcherish.workclock.bean.data.RecordAdapterHeadBean;
import com.android.wellcherish.workclock.util.CommonUtil;
import java.util.ArrayList;
import java.util.List;

/**
 * 此 Adapter 实现的是一个二级的可展开的 Adapter
 *
 * @author 张文琛
 * @date 2019/11/8 21:14
 */
public class RecordAdapter extends RecyclerView.Adapter<RecordBaseViewHolder> {
    private static final String TAG = "RecordAdapter";

    private Context context;
    private List<GroupRecord> originalData;
    private List<GroupRecord> data;
    /**
     * 列表是否能折叠的标识，默认可折叠
     * */
    private boolean canFold = true;

    public RecordAdapter(Context context, List<GroupRecord> data) {
        this.context = context;
        Log.d(TAG, "构造函数 data = " + data);
        originalData = getNewData(data);
        this.data = data;
    }

    public void setData(List<GroupRecord> data) {
        Log.d(TAG, "new data = " + data);
        originalData = getNewData(data);
        this.data = data;
        // 刷新
        notifyDataSetChanged();
    }

    public void setCanFold(boolean canFold) {
        this.canFold = canFold;
    }

    @NonNull @Override
    public RecordBaseViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        Log.d(TAG, "创建, viewType = " + viewType);

        LayoutInflater inflater = LayoutInflater.from(context);

        if(viewType == RecordBaseViewHolder.ViewType.HEAD) {
            // 头布局
            return new RecordHeadViewHolder(context, inflater
                .inflate(R.layout.list_item_head, viewGroup, false));
        } else if (viewType == RecordBaseViewHolder.ViewType.CONTENT){
            // 内容布局
            return new RecordContentViewHolder(context, inflater
                .inflate(R.layout.list_item_content, viewGroup, false));
        } else {
            return new RecordUnknownViewHolder(context, inflater
                .inflate(R.layout.list_item_unknown, viewGroup, false));
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecordBaseViewHolder recordViewHolder, final int position) {
        int type = getItemViewType(position);
        Log.d(TAG, "绑定, type = " + type);
        if(recordViewHolder instanceof RecordUnknownViewHolder) {
            return;
        }

        final GroupRecord record = getGroupRecord(position);

        recordViewHolder.onBindViewHolder(getItem(position), position);

        if(type == RecordBaseViewHolder.ViewType.HEAD) {
            // 头布局设置点击事件
            final RecordHeadViewHolder holder = (RecordHeadViewHolder) recordViewHolder;
            holder.getView().setOnClickListener(
                new View.OnClickListener() {
                    @Override public void onClick(View v) {
                        if(!canFold) {
                            // 不能被折叠，点击事件不生效
                            return;
                        }
                        if(CommonUtil.isEmptyList(record.getData())) {
                            return;
                        }
                        if(record.isFold()) {
                            // 折叠，点击后成为非折叠
                            record.setFold(false);
                            // 符号变成减号
                            ((RecordAdapterHeadBean)getItem(position)).setIconRes(R.drawable.ic_delete_default);
                            holder.ivMode.setImageDrawable(context.getDrawable(R.drawable.ic_delete_default));
                            //notifyItemRangeRemoved(position,record.getData().size());
                            // 需要增加数据项
                            addItem(record);
                        } else {
                            // 非折叠，点击后成为折叠
                            record.setFold(true);
                            // 符号变成加号
                            ((RecordAdapterHeadBean)getItem(position)).setIconRes(R.drawable.ic_add_default);
                            holder.ivMode.setImageDrawable(context.getDrawable(R.drawable.ic_add_default));
                            //notifyItemRangeInserted(position,record.getData().size());
                            // 需要清除数据项
                            removeItem(record);
                        }
                        //notifyItemRangeChanged(position,record.getData().size());
                        // 方案2
                        notifyDataSetChanged();
                    }
                });
        }
    }

    @Override public int getItemViewType(int position) {
        int type;
        if(isPositionIllegal(position)) {
            type = RecordBaseViewHolder.ViewType.UNKNOWN;
        } else {
            if (isHeadPosition(position)) {
                type = RecordBaseViewHolder.ViewType.HEAD;
            } else {
                type = RecordBaseViewHolder.ViewType.CONTENT;
            }
        }
        Log.d(TAG, "itemType = " + type + ", position = " + position);
        return type;
    }

    @Override public int getItemCount() {
        if(CommonUtil.isEmptyList(data)) {
            return 0;
        }
        int itemCount = 0;

        List<IBaseBean> dataList;
        for(GroupRecord bean : data) {
            if(bean == null || CommonUtil.isEmptyList(bean.getData())) {
                continue;
            }

            dataList = bean.getData();
            itemCount += dataList.size();
        }

        Log.d(TAG, "getItemCount---itemCount = " + itemCount);

        return itemCount;
    }

    public IBaseBean getItem(int position) {
        if(isPositionIllegal(position) || CommonUtil.isEmptyList(data)) {
            return null;
        }
        int startIndex = 0;
        for(GroupRecord bean : data) {
            if(bean == null || CommonUtil.isEmptyList(bean.getData())) {
                return null;
            }
            for(IBaseBean baseBean : bean.getData()) {
                // 双循环，遍历所有item
                if(position == startIndex) {
                    return baseBean;
                }
                // 取了一个item，Index加一
                startIndex += 1;
            }
        }
        return null;
    }

    public GroupRecord getGroupRecord(int position) {
        if(CommonUtil.isEmptyList(data) || isPositionIllegal(position)) {
            return null;
        }

        IBaseBean item = getItem(position);

        for(GroupRecord bean : data) {
            if(bean.getData().contains(item)) {
                return bean;
            }
        }

        return null;
    }

    /**
     * 判断position 是否是头布局的 position
     * */
    public boolean isHeadPosition(int position) {
        if(isPositionIllegal(position) || CommonUtil.isEmptyList(data)) {
            return false;
        }
        if(position == 0) {
            return true;
        }

        if (getItem(position) instanceof RecordAdapterHeadBean) {
            return true;
        }
        return false;
    }

    public boolean isPositionIllegal(int position) {
        return position < 0 || position >= getItemCount();
    }

    private void removeItem(GroupRecord record) {
        if(record == null) {
            return;
        }
        record.getData().clear();
        int index = originalData.indexOf(record);
        record.addDataItem(originalData.get(index).getData().get(0));
    }

    private void addItem(GroupRecord record) {
        if(record == null) {
            return;
        }
        record.getData().clear();
        int index = originalData.indexOf(record);
        record.setData(new ArrayList<>(originalData.get(index).getData()));
    }

    private List<GroupRecord> getNewData(List<GroupRecord> data) {
        if(data == null) {
            return null;
        }
        List<GroupRecord> newData = new ArrayList<>();
        GroupRecord newItem;
        List<IBaseBean> itemData;
        for(GroupRecord record : data) {
            itemData = new ArrayList<>(record.getData());
            newItem = new GroupRecord(record.getGroupId(), itemData);
            newData.add(newItem);
        }
        return newData;
    }
}
